

from ..models.textbook_model import Textbook
from ..models.folder_sources import FolderSources
from sqlalchemy.orm import Session
from sqlalchemy import select
from fastapi import HTTPException

from ..models.images_model import Images
from ..models.paper_model import Paper
from ..models.ppts_model import Ppts
from ..models.videos_model import Videos
from ..models.voices_model import Voices


def create_folder_source(db: Session, folder_id: int, resource_type: str, resource_id: int):
    stmt = select(FolderSources).where(
        FolderSources.folder_id == folder_id,
        FolderSources.resource_type == resource_type,
        FolderSources.resource_id == resource_id
    )
    old_source = db.execute(stmt).scalars().all()
    if old_source:
        raise HTTPException(status_code=400, detail="Resource already exists")
    new_source = FolderSources(
        folder_id=folder_id,
        resource_type=resource_type,
        resource_id=resource_id
    )
    db.add(new_source)
    db.commit()
    db.refresh(new_source)
    return new_source
def update_folder_source(db: Session, source_id: int, folder_id: int = None, resource_type: str = None, resource_id: int = None):
    source = db.query(FolderSources).filter(FolderSources.id == source_id).first()
    if not source:
        return None

    if folder_id is not None:
        source.folder_id = folder_id
    if resource_type is not None:
        source.resource_type = resource_type
    if resource_id is not None:
        source.resource_id = resource_id

    db.commit()
    db.refresh(source)
    return source
def delete_folder_source(db: Session,folder_id: int, resource_id: int,resource_type: str):
    source = db.query(FolderSources).filter(FolderSources.resource_id == resource_id,
                                            FolderSources.resource_type == resource_type ,
                                            FolderSources.folder_id == folder_id).first()
    if not source:
        raise HTTPException(status_code=404, detail="Resource not found")
    db.delete(source)
    db.commit()
    return source.as_dict()


def get_resources_by_folder_id(db: Session, folder_id: int):
    """
    根据 folder_id 获取所有相关资源，并根据 resource_type 和 resource_id 获取具体资源详情。

    参数:
        db: 数据库会话
        folder_id: 文件夹 ID

    返回:
        List[dict]: 每个元素为一个资源的详细信息字典
    """
    # 1. 根据 folder_id 获取所有相关资源记录
    folder_sources = db.query(FolderSources).filter(FolderSources.folder_id == folder_id).all()

    resources = []

    for source in folder_sources:
        resource_info = []

        # 2. 根据 resource_type 判断资源类型并查询具体资源表
        if source.resource_type == "textbook":
            textbook = db.query(Textbook).filter(Textbook.id == source.resource_id).first()
            if textbook:
                resource_info.append(textbook.as_dict())
        elif source.resource_type == "paper":
            paper = db.query(Paper).filter(Paper.id == source.resource_id).first()
            if paper:
                resource_info.append(paper.as_dict())
        elif source.resource_type=="image":
            image = db.query(Images).filter(Images.id == source.resource_id).first()
            if image:
                resource_info.append(image.as_dict())
        elif source.resource_type=="video":
            video = db.query(Videos).filter(Videos.id == source.resource_id).first()
            if video:
                resource_info.append(video.as_dict())
        elif source.resource_type=="ppt":
            ppt  = db.query(Ppts).filter(Ppts.id == source.resource_id).first()
            if ppt:
                resource_info.append(ppt.as_dict())
        elif source.resource_type=="voice":
            voice = db.query(Voices).filter(Voices.id == source.resource_id).first()
            if voice:
                resource_info.append(voice.as_dict())
        resources.append(resource_info)

    return resources

def sort_resources_by_name_prefix(resources, prefix):
    # 使用 lambda 表达式对列表进行排序
    sorted_resources = sorted(
        resources,
        key=lambda resource: not resource[0]['name'].startswith(prefix)
    )
    return sorted_resources

def move_resource(db: Session, resource_id: int, resource_type:str,new_folder_id: int):
    folder_source = db.query(FolderSources).filter(FolderSources.resource_id == resource_id,
                                               FolderSources.resource_type == resource_type).first()
    if folder_source:
        folder_source.folder_id =new_folder_id
        db.commit()
    else:
        raise HTTPException(status_code=404, detail="Resource not found")
    return folder_source.as_dict()

if __name__ == "__main__":
    from database.db import SessionLocal
    db=SessionLocal()
    a=delete_folder_source(db,2,23,"image")
